import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
// https://vite.dev/config/
const pathSrc = path.resolve(__dirname, 'src')
export default defineConfig(({ command, mode }) => {
  // 获取环境变量
  let env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      // vue调试工具
      vueDevTools(),
      // element Plus自动导入
      AutoImport({
        imports: ['vue'],
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({prefix: 'Icon'})
        ],
        dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
      }),
      Components({
        // 1.配置elementPlus采用sass样式配色系统
        resolvers: [
          ElementPlusResolver({importStyle: 'sass'}),
          IconsResolver({enabledCollections: ['ep']})
        ],
      }),
      Icons({
        autoInstall: true,
      }),
      // svg
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: "icon-[dir]-[name]"
      }),
      // mock
      viteMockServe({
        localEnabled: command === 'serve'
      })
    ],
    resolve: {
      alias: {
        '@': path.resolve("./src")
        // '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptOptions: true,
          additionalData: `@use "@/styles/element/index.scss" as *; @use "@/styles/variable.scss";`,
        },
      },
    },
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_SERVE,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        }
      }
    }
  }
})
